package app.cloudstringers;

import utils.Utils;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;

import com.google.android.gms.gcm.GoogleCloudMessaging;

import controller.LoginAsync;
import controller.RegisterGCMClientAsync;
import define.Constants;
import define.DefaultValue;
import define.Key;
import define.SharedPreference;

public class Login extends Activity {
	/**
	 * String section
	 */
	public static String USER_NAME = null, PASWORD = null, GLOBAL_ID = null;

	// GCM
//	private final String EXTRA_MESSAGE = "message";
	private String regid;

	private static final String TAG = Home.class.getSimpleName();

	/**
	 * View section
	 */
	private AlertDialog.Builder mAdConnection, mAdLoginFail, mAdExit;
	private EditText mEtEmail, mEtPassword;

	/**
	 * The others section
	 */
	private GoogleCloudMessaging gcm;
	
	/**
	 * Clicked button
	 */
	public void onClickLogin(View v) {
		switch (v.getId()) {
		case R.id.btn_login:
			// Set the cursor to the first index
			mEtEmail.setSelection(0);

			// Show progress dialog to wait
			if (!mEtEmail.getText().toString().equals("")
					&& !mEtPassword.getText().toString().equals("")) {
				USER_NAME = mEtEmail.getText().toString();
				PASWORD = mEtPassword.getText().toString();

				// call new thread to login account
				new LoginAsync(this)
				.execute(GLOBAL_ID, USER_NAME, PASWORD, regid, define.Login.ANDROID);
			} else {
				// Notify the user to fill in the blank
				mAdLoginFail.show();
			}
			break;
		default:
			break;
		}
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.page_login);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);

		// Initialize connectivity utility
		Constants.utils = new Utils(this);

		// Hidden keyboard
		Constants.utils.hideSoftKeyboard(this);

		// Initial alert dialogs
		initialAlertDialog();

		// Initial variables
		initialVariables();

		// Get data from shared preferences
		SharedPreferences mSpSettings;
		mSpSettings = getSharedPreferences(SharedPreference.PREFS,
				Context.MODE_PRIVATE);

		if (!mSpSettings.getAll().isEmpty()) {
			// Get id & user name
			GLOBAL_ID = mSpSettings.getString(
					SharedPreference.PREFS_KEY_GLOBAL_ID,
					DefaultValue.DEFAULT_GLOBAL_ID + "");
			USER_NAME = mSpSettings.getString(
					SharedPreference.PREFS_KEY_LOGIN_NAME,
					Key.KEY_CANNOT_BUY_CANNOT_SELL + "");
		}
		
		/**
		 * Google Cloud Messaging feature
		 * Begin register ID, or if register ID already exists, use it
		 */
		setUpGCM(this);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();

		GLOBAL_ID = DefaultValue.DEFAULT_GLOBAL_ID;
	}

	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_ENTER) {
			// Set the cursor to the first index
			mEtEmail.setSelection(0);
		}

		return super.onKeyUp(keyCode, event);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			mAdExit.show();
		}

		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onResume() {
		if (Constants.utils.isNetworkOnline()) {
			// Set email
			if (USER_NAME != null
					&& !USER_NAME.equals(Key.KEY_CANNOT_BUY_CANNOT_SELL)) {
				mEtEmail.setText(USER_NAME);
			}

			if (GLOBAL_ID != null
					&& !GLOBAL_ID.equals(DefaultValue.DEFAULT_GLOBAL_ID)) {
				
				// new intent to Home page
				Intent intent = new Intent(Login.this, Home.class);

				// finish Login page
				finish();

				// new intent to Home page
				startActivity(intent);
			}
		} else {
			// Show error connection dialog
			mAdConnection.show();
		}

		super.onResume();
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		if (event.getAction() == MotionEvent.ACTION_DOWN) {
			Constants.utils.hideSoftKeyboard(mEtEmail);
			Constants.utils.hideSoftKeyboard(mEtPassword);

			// Set the cursor to the first index
			mEtEmail.setSelection(0);
		}

		return super.onTouchEvent(event);
	}

	/**
	 * Initial methods
	 */
	private void initialVariables() {
		mEtEmail = (EditText) findViewById(R.id.et_user_name);
		mEtPassword = (EditText) findViewById(R.id.et_password);
	}

	private void initialAlertDialog() {
		mAdConnection = new AlertDialog.Builder(this);
		mAdConnection.setTitle(getString(R.string.title_failed_connection));
		mAdConnection.setIcon(R.drawable.ibtn_error_normal);
		mAdConnection.setCancelable(false);
		mAdConnection
		.setMessage(getString(R.string.content_failed_server_connection));
		mAdConnection.setPositiveButton(R.string.try_again,
				new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog9, int whichButton) {
				// New intent to wireless setting
				startActivity(new Intent(
						android.provider.Settings.ACTION_WIRELESS_SETTINGS));
			}
		});
		mAdConnection.setNegativeButton(R.string.quit,
				new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog9, int whichButton) {
				android.os.Process.killProcess(android.os.Process
						.myPid());
			}
		});

		mAdLoginFail = new AlertDialog.Builder(this);
		mAdLoginFail.setTitle(getString(R.string.title_failed_connection));
		mAdLoginFail.setIcon(R.drawable.ibtn_error_normal);
		mAdLoginFail.setCancelable(false);
		mAdLoginFail
		.setMessage(getString(R.string.content_wrong_username_password));
		mAdLoginFail.setPositiveButton(R.string.try_again,
				new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog9, int whichButton) {
			}
		});
		mAdLoginFail.setNegativeButton(R.string.quit,
				new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog9, int whichButton) {
				android.os.Process.killProcess(android.os.Process
						.myPid());
			}
		});

		mAdExit = new AlertDialog.Builder(Login.this);
		mAdExit.setTitle(R.string.title_exit);
		mAdExit.setIcon(R.drawable.ic_info_normal);
		mAdExit.setCancelable(false);
		mAdExit.setMessage(R.string.content_exit);
		mAdExit.setPositiveButton(R.string.ok,
				new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog9, int whichButton) {
				android.os.Process.killProcess(android.os.Process
						.myPid());
			}
		});
		mAdExit.setNegativeButton(R.string.cancel,
				new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog9, int whichButton) {
			}
		});
	}

	/**
	 * Basic methods
	 */

	private void setUpGCM(Context context) {
		gcm = GoogleCloudMessaging.getInstance(this);
		regid = getRegistrationId(context);

		if (regid.isEmpty()) {
			new RegisterGCMClientAsync(Login.this, gcm, define.Login.SENDER_ID, regid).execute();
		}
	}

	/**
	 * Gets the current registration ID for application on GCM service.
	 * <p>
	 * If result is empty, the app needs to register.
	 *
	 * @return registration ID, or empty string if there is no existing
	 *         registration ID.
	 */
	private String getRegistrationId(Context context) {
		final SharedPreferences prefs = getGCMPreferences(context);
		String registrationId = prefs.getString(define.Login.PROPERTY_REG_ID, "");

		if (registrationId.isEmpty()) {
			Log.i(TAG, "Registration not found.");
			return "";
		}

		// Check if app was updated; if so, it must clear the registration ID
		// since the existing regID is not guaranteed to work with the new
		// app version.
		int registeredVersion = prefs.getInt(define.Login.PROPERTY_APP_VERSION, Integer.MIN_VALUE);
		int currentVersion = getAppVersion(context);
		if (registeredVersion != currentVersion) {
			Log.i(TAG, "App version changed.");
			return "";
		}
		return registrationId;
	}

	/**
	 * @return Application's {@code SharedPreferences}.
	 */
	private SharedPreferences getGCMPreferences(Context context) {
		// This sample app persists the registration ID in shared preferences, but
		// how you store the regID in your app is up to you.
		return getSharedPreferences(Home.class.getSimpleName(),
				Context.MODE_PRIVATE);
	}

	/**
	 * @return Application's version code from the {@code PackageManager}.
	 */
	private static int getAppVersion(Context context) {
		try {
			PackageInfo packageInfo = context.getPackageManager()
					.getPackageInfo(context.getPackageName(), 0);
			return packageInfo.versionCode;
		} catch (NameNotFoundException e) {
			// should never happen
			throw new RuntimeException("Could not get package name: " + e);
		}
	}
}